package com.health.mapp.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.ImMsgNotice;
import com.health.db.model.ImMsgNoticeExample;
import com.health.db.model.UserLIST;
import com.health.db.service.msg.ImMsgNoticeService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.GetStuffOpenIdResp;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.StuffBindReq;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;
import com.wxtools.api.IService;
import com.wxtools.bean.result.WxError;
import com.wxtools.bean.result.WxOAuth2AccessTokenResult;

/**
 * Created by yangyayun on 2018/1/11.
 */
public class StuffBindImpl implements ActionInterface{


    private IService mpService;
    private IUserLISTService userLISTService;
    private IStuffListService stuffListService;
    private ImMsgNoticeService imMsgNoticeService  ;


    @Override
    public Response execute(Header header, Object reqBean) throws Exception {

        StuffBindReq req = (StuffBindReq) reqBean;
        GetStuffOpenIdResp _resp = new GetStuffOpenIdResp();

        if (StringUtils.isBlank(req.getUserPhone())||
                StringUtils.isBlank(req.getSmsCode()) ||
                null == req.getTokenResult()) {

            _resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
            _resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
            return _resp;
        }

        UserLIST user = null;
        StuffDetailDto stuffDetail = stuffListService.selectByStuffNo(req.getUserPhone());
        if (null!=stuffDetail)
        {
            user = userLISTService.selectByUserId(stuffDetail.getStuffid());
        }

        if (null != user) {

            //检验是否意见绑定了其他手机号
            List<UserLIST> userLISTS = userLISTService.selectByWXOpenid(req.getTokenResult().getOpenid());
            if (null != userLISTS && userLISTS.size() > 0 && !userLISTS.get(0).getUserNo().equals(req.getUserPhone())) {
                _resp.setErrorCode(-1);
                _resp.setErrorMsg("该微信账户已绑定其他账号");
                return _resp;
            }

            //校验短信验证码
            ImMsgNoticeExample notice = new ImMsgNoticeExample();
            notice.setRandom(req.getSmsCode());
            notice.setNoticeReceiveAddress(req.getUserPhone());
            notice.setIsUsedFlag((short) 1);
            notice.setModetypeid(9);
            List<ImMsgNotice> list=imMsgNoticeService.selectByExample(notice);

            if (list.size()!=1) {
                _resp.setErrorCode(ResultCode.SMS_ERROR);
                _resp.setErrorMsg(ResultCode.SMS_ERROR_NOTE);
                return _resp;
            }

            //校验是否openid正确
            WxError wxError=mpService.oauth2CheckAccessToken(req.getTokenResult().getAccess_token(),req.getTokenResult().getOpenid());
            if (wxError.getErrcode()==0)
            {
                user.setWxopenid(req.getTokenResult().getOpenid());
                int result=userLISTService.updateByPrimaryKey(user);
                if (result>0)
                {
                    //绑定成功
                    return _resp;
                }else
                {
                    _resp.setErrorCode(-1);
                    _resp.setErrorMsg("绑定失败");
                    return _resp;
                }

            }else
            {
                try {
                    //强制刷新
                    WxOAuth2AccessTokenResult tokenResult= mpService.oauth2ToGetRefreshAccessToken(req.getTokenResult().getRefresh_token());
                    user.setWxopenid(tokenResult.getOpenid());
                    int result=userLISTService.updateByPrimaryKey(user);
                    if (result>0)
                    {
                        //绑定成功
                        return _resp;
                    }else
                    {
                        _resp.setErrorCode(-1);
                        _resp.setErrorMsg("绑定失败");
                        return _resp;
                    }

                }catch (Exception e)
                {
                    _resp.setErrorCode(-100);
                    _resp.setErrorMsg("绑定超时");
                    return _resp;
                }

            }

        }else
        {
            _resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS);
            _resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS_NOTE);
            return _resp;
        }

    }
}
